<template>
  <el-card>
    <template #header>
      <span>检测属性</span>
      <el-button @click="handleManualEntry" style="float: right" type="warning"
        >{{ manualEntryFlag ? "自动录入" : "手动录入" }}
      </el-button>
    </template>
    <el-descriptions :column="2">
      <el-descriptions-item label="收缩压">
        <template v-if="manualEntryFlag">
          <el-input-number v-model="bloodInfo.systolic" />
        </template>
        <template v-else>
          {{ bloodInfo.systolic }}
        </template>
      </el-descriptions-item>
      <el-descriptions-item label="舒张压">
        <template v-if="manualEntryFlag">
          <el-input-number v-model="bloodInfo.diastolic" />
        </template>
        <template v-else>
          {{ bloodInfo.diastolic }}
        </template>
      </el-descriptions-item>

      <el-descriptions-item label="心率">
        <template v-if="manualEntryFlag">
          <el-input-number v-model="bloodInfo.heartRate" />
        </template>
        <template v-else>
          {{ bloodInfo.heartRate }}
        </template>
      </el-descriptions-item>
      <el-descriptions-item label="时间">
        <template v-if="manualEntryFlag">
          <el-date-picker
            type="datetime"
            :clearable="false"
            v-model="bloodInfo.measureTime"
          />
        </template>
        <template v-else>
          {{ timeFormatter(bloodInfo.measureTime) }}
        </template>
      </el-descriptions-item>
    </el-descriptions>
  </el-card>
  <br />
  <el-alert
    :title="bluetoothDesc.info"
    :closable="false"
    :type="bluetoothDesc.type"
  />
  <el-card :body-style="{ textAlign: 'center' }">
    <el-button
      size="default"
      :disabled="!props.qrCodeInfo.idno"
      type="success"
      @click="handleRecordSave"
      >保存记录</el-button
    >&nbsp;&nbsp;
    <el-button
      size="default"
      type="danger"
      @click="connectToDeviceAndSubscribeToUpdates"
      :disabled="!qrCodeInfo.id"
      >开始测量 </el-button
    >&nbsp;&nbsp;
    <el-button
      size="default"
      type="info"
      @click="clearCacheDevice"
      :disabled="!cacheDeviceId"
      >清除缓存</el-button
    >
  </el-card>

  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    v-model="bluetoothDialog.visible"
    :title="cacheDeviceId ? '正在搜索蓝牙，请稍等' : '请选择一个蓝牙设备'"
    width="50%"
  >
    <ul>
      <li v-for="item in bluetoothList" v-bind:key="item.deviceId">
        <el-radio-group v-model="bluetoothDialog.cacheDeviceId">
          <el-radio :label="item.deviceId">{{ item.deviceName }}</el-radio>
        </el-radio-group>
      </li>
    </ul>
    <template #footer v-if="!cacheDeviceId">
      <span class="dialog-footer">
        <el-button @click="bluetoothDialog.handleClose" type="warning"
          >关闭</el-button
        >
        <el-button type="success" @click="bluetoothDialog.handleOk"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
// 缓存的设备，刚登陆系统选择一次设备
import { computed, onMounted, reactive, ref } from "vue";
import { IBluetooth, IBluetoothDesc } from "./types";
import { ipcRenderer } from "electron";
import { ElNotification } from "element-plus";
import dayjs from "dayjs";
import { IQRCodeInfo } from "@/model/IQRCodeInfo";
import {IBloodPressCloud} from "@/model/TerminalType";
const timeFormatter = (value) => {
  return value ? dayjs(value).format("YYYY-MM-DD HH:mm:ss") : "";
};
const props = defineProps<{
  qrCodeInfo: Partial<IQRCodeInfo>;
}>();

const emits = defineEmits(["save"]);
const bloodInfo = ref<Partial<IBloodPressCloud>>({});
const manualEntryFlag = ref(false);
const handleManualEntry = () => {
  if (!manualEntryFlag.value) {
    manualEntryFlag.value = true;
    bloodInfo.value.measureTime = bloodInfo.value.measureTime || Date.now();
  } else {
    manualEntryFlag.value = false;
  }
};

const cacheDeviceId = ref("");

// 蓝牙状态描述
const bluetoothDesc = ref<IBluetoothDesc>({
  type: "success",
  info:
    "蓝牙未连接，请点击开始测量按钮！" +
    (cacheDeviceId.value !== "" ? "(已缓存设备)" : "(未缓存设备)"),
});
const clearCacheDevice = () => {
  cacheDeviceId.value = "";
};
// 弹框选择蓝牙
const bluetoothDialog = reactive({
  visible: false,
  cacheDeviceId: cacheDeviceId.value,
  handleClose: function () {
    bluetoothDialog.visible = false;
    ipcRenderer.send("bluetooth-select-done", "");
  },
  handleOk() {
    bluetoothDialog.visible = false;
    bluetoothList.value = [];
    cacheDeviceId.value = bluetoothDialog.cacheDeviceId;
    ipcRenderer.send("bluetooth-select-done", bluetoothDialog.cacheDeviceId);
  },
});

const bluetoothList = ref<Array<IBluetooth>>();
const nav = window.navigator as any;
/**------------------------蓝牙相关start-------------------- */
// 0x1810  0x2A49血压功能  0x2A35血压测量
const BLOOD_PRESSURE = "00001810-0000-1000-8000-00805f9b34fb";
const BLOOD_PRESSURE_MEASUREMENT = "00002a35-0000-1000-8000-00805f9b34fb";
// const CONNECT_ORDER = "cc80020301010001"
// const POWER_ORDER = "cc80020304040001"
// const START_MEASURE = "cc80020301020002"
// const STOP_ORDER = "cc80020301030003"
let bluetoothDevice: any = null;

// 点击开始测量，先搜索蓝牙，连接蓝牙，发送执行开始测量
const connectToDeviceAndSubscribeToUpdates = async () => {
  manualEntryFlag.value = false;
  try {
    console.log("打开选择弹框之前，先关闭之前的蓝牙连接！");
    if (bluetoothDevice && bluetoothDevice.gatt.connected === true) {
      const data = await bluetoothDevice.gatt.disconnect();
      console.log("关闭了之前的蓝牙", data);
    }
  } catch (e) {
    console.log("手动关闭蓝牙连接失败", e);
  }
  // 打开选择蓝牙的弹框
  bluetoothDialog.visible = true;
  bluetoothList.value = [];
  console.log("打开弹框，选择设备");
  try {
    console.log("开始搜索设备");
    bluetoothDesc.value.info = "正在选择蓝牙，请稍后...";
    bluetoothDevice = await nav.bluetooth.requestDevice({
      filters: [{ services: [BLOOD_PRESSURE] }],
      acceptAllDevices: false,
    });
    // bluetoothDevice = await nav.bluetooth.requestDevice({
    //   acceptAllDevices: true
    // })
    bluetoothDialog.visible = false;
    console.log("完成设备选择", bluetoothDevice);
    bluetoothDevice.addEventListener("gattserverdisconnected", onDisconnected);
  } catch (error) {
    console.log(error);
    bluetoothDialog.visible = false;
    ElNotification({
      type: "error",
      title: "设备连接失败",
      message: "设备连接不成功，请确认终端蓝牙正常！",
    });
    ipcRenderer.send("cancel-bluetooth-select");
    return;
  }
  try {
    const bluetoothServer = await bluetoothDevice.gatt.connect();
    bluetoothDesc.value.info = "蓝牙已连接，正在测量中...";
    const bluetoothService = await bluetoothServer.getPrimaryService(
      BLOOD_PRESSURE
    );
    console.log("service", bluetoothService);
    const characteristic = await bluetoothService.getCharacteristic(
      BLOOD_PRESSURE_MEASUREMENT
    );
    characteristic.addEventListener(
      "characteristicvaluechanged",
      handleCharacteristicValueChanged
    );
    console.log(characteristic);
    await characteristic.startNotifications();
    // console.log(instance);
  } catch (error) {
    console.log(`There was an error: ${error}`);
  }
};

const handleCharacteristicValueChanged = async (event) => {
  console.log(event.target.value);
  const data = event.target.value;
  // bloodInfo.
  bloodInfo.value.systolic = data.getUint8(1);
  bloodInfo.value.diastolic = data.getUint8(3);
  bloodInfo.value.heartRate = data.getUint8(14);
  bloodInfo.value.measureTime = Date.now();
  if (bluetoothDevice && bluetoothDevice.gatt.connected === true) {
    const data = await bluetoothDevice.gatt.disconnect();
    console.log("关闭了之前的蓝牙", data);
  }
  handleRecordSave();
};

onMounted(() => {
  ipcRenderer.on(
    "send-bluetooth-device-list",
    (event, dataList: Array<IBluetooth>) => {
      console.log("1111111111", cacheDeviceId.value);
      if (cacheDeviceId.value !== "") {
        const cacheDevice = dataList.find((item) => {
          return item.deviceId === cacheDeviceId.value;
        });
        console.log("cacheDevice", cacheDevice);
        if (cacheDevice) {
          ipcRenderer.send("bluetooth-select-done", cacheDeviceId.value);
        }
        return;
      } else {
        bluetoothList.value = dataList;
      }
    }
  );
});
// 断开连接
const onDisconnected = () => {
  bluetoothDesc.value.info = "蓝牙未连接，请点击开始测量按钮！";
  console.log("断开蓝牙连接");
};

const handleRecordSave = async () => {
  manualEntryFlag.value = false;
  emits("save", bloodInfo.value);
};
const resetData = () => {
  bloodInfo.value = {};
};
defineExpose({ resetData });
</script>

<style scoped></style>
